package com.gogowan.agroenterprise;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;
import it.sauronsoftware.ftp4j.FTPListParseException;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationResultInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.NcpFile;
import com.gogowan.agroenterprise.model.NcpRequestInfo;
import com.gogowan.agroenterprise.model.PicturesInfo;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.VideoInfo;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.OperationPicturesGridView;
import com.gogowan.agroenterprise.widget.OperationVideoGridView;
import com.gogowan.agroenterprise.widget.PicturesGridView;
import com.gogowan.agroenterprise.widget.VideoGridView;

public class SpectorActivity extends BaseActivity {

	private Button paiMa;
	private Spinner batchs;
	private Spinner batchsSec;
	private Spinner isPublicOrSec;
	private boolean isPublic = true;
	// private EditText personInDeal;
	private EditText spectorName;
	private EditText spectorContent;
	private OperationPicturesGridView picGrid;
	private OperationVideoGridView videoGrid;

	private Button saveToUpload;
	private Button backToIndex;

	private SharedPreferences preferences;
	private long enterpriseId;
	private List<MaterialBatch> batches;
	private List<MaterialBatch> batchesSec;
	private long selectedBatchId;
	private long selectedBatchSecId;
	// 此字段存储ftp上传的文件存放的目录
	private String ftpFile;
	private ProgressDialog progressDialog;
	private CodeActivationResultInfo codeActivationResultInfo;
	private List<NcpFile> ncpFiles;
	private String usercode;
	private String username;
	private boolean isNew;
	private long personId;

	private ExpandableListView expandableListView;
	private List<String> groupArray;
	private ArrayList<List<View>> childArray;
	private LinearLayout chileView06;

	private ImageButton paizhaoBtn;
	private ImageButton shexiangBtn;
	private TextView picNewsTextView;
	private TextView vioNewsTextView;
	private ArrayAdapter<String> adapter;
	private ScrollView spectorScroll;
	private FTPClient ftp;
//	private String domainName = null;
//	private String name = null;
//	private String pwd = null;
	private String[] list = null;
	
	private Handler mHandler = new Handler();
	private Button backBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.spector);

		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		ftpFile = preferences.getString("ftpfile", "OE493");

		// new Thread(runnable).start();

		// batches = getIntent().getParcelableArrayListExtra("batches");

		String content01 = getIntent().getStringExtra("batches");

		CodeActivationResultInfo codeActivationResultInfo = (CodeActivationResultInfo) Utils
				.fromJSON(content01, CodeActivationResultInfo.class);

		batches = codeActivationResultInfo.getBatchList();
		backBtn = (Button) findViewById(R.id.spector_backBtn);
		backBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SpectorActivity.this.finish();

			}
		});
		LoadListDate();
		// expandableListView = (ExpandableListView)
		// findViewById(R.id.spector_elist);
		// // expandableListView.setGroupIndicator(null);
		// expandableListView.setAdapter(new ExpandableAdapter(this));
		// int groupCount = expandableListView.getCount();
		// for (int i = 0; i < groupCount; i++) {
		// expandableListView.expandGroup(i);
		// }
		//
		// setListViewHeight(expandableListView);
		//
		// expandableListView.setOnGroupExpandListener(groupExpandListener);
		// expandableListView.setOnGroupCollapseListener(groupCollListener);

		// paiMa = (Button) findViewById(R.id.spector_btn_paima);

		picGrid = (OperationPicturesGridView) findViewById(R.id.spector_pic_grid);
		picGrid.setLisenter(SpectorActivity.this);
		videoGrid = (OperationVideoGridView) findViewById(R.id.spector_video_grid);
		videoGrid.setOperation(SpectorActivity.this);
		saveToUpload = (Button) findViewById(R.id.spector_save);
		backToIndex = (Button) findViewById(R.id.spector_cancel);

		paizhaoBtn = (ImageButton) findViewById(R.id.spector_paizhao);
		shexiangBtn = (ImageButton) findViewById(R.id.spector_shexiang);

		picNewsTextView = (TextView) findViewById(R.id.spector_pic_news);
		vioNewsTextView = (TextView) findViewById(R.id.spector_vio_news);

		// paiMa.setFocusable(true);
		// paiMa.requestFocus();
		// paiMa.setFocusableInTouchMode(true);
		//

		isNew = preferences.getBoolean("isNew", false);
		personId = preferences.getLong("personid", 0);



		spectorName.setText(MyApplication.mSettings.getString("username","")
				.toString());
		//usercode = loginResultInfo.getUserinfo().getUsercodenum();
		username = MyApplication.mSettings.getString("username","");

		/**
		 * 公共/子批次初始值
		 */
		String[] m2 = new String[2];
		m2[0] = "公共";
		m2[1] = "子批次";
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(
				SpectorActivity.this, R.layout.simple_spinner_item, m2);
		// 设置下拉列表的风格
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到spinner中
		isPublicOrSec.setAdapter(adapter2);

		/**
		 * 生产批次
		 */
		if (batches == null || batches.size() == 0) {
			Toast.makeText(SpectorActivity.this, "批次列表空", Toast.LENGTH_LONG)
					.show();
		} else {

			String[] m = new String[batches.size()];
			for (int i = 0; i < batches.size(); i++) {
				m[i] = batches.get(i).getBatchcode();
			}
			adapter = new ArrayAdapter<String>(SpectorActivity.this,
					R.layout.simple_spinner_item, m);
			// 设置下拉列表的风格
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			// 将adapter 添加到spinner中
			batchs.setAdapter(adapter);
		}

		// 公共、子批次
		isPublicOrSec
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0,
							View arg1, int arg2, long arg3) {
						if (arg2 == 0) {
							isPublic = true;
							chileView06.setVisibility(View.GONE);
							// setListViewHeight(expandableListView);
						} else if (arg2 == 1) {
							isPublic = false;
							chileView06.setVisibility(View.VISIBLE);
							// setListViewHeight(expandableListView);
						}
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

		batchs.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				selectedBatchId = batches.get(position).getBatchid();

				batchesSec = batches.get(position).getBactchList();
				if (batchesSec != null && batchesSec.size() > 0) {
					batchsSec.setClickable(true);
					batchsSec.setEnabled(true);
					String[] m = new String[batchesSec.size()];
					for (int i = 0; i < batchesSec.size(); i++) {
						m[i] = batchesSec.get(i).getBatchcode();
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							SpectorActivity.this,
							R.layout.simple_spinner_item, m);
					// 设置下拉列表的风格
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					// 将adapter 添加到spinner中
					batchsSec.setAdapter(adapter);

					batchsSec
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								@Override
								public void onItemSelected(
										AdapterView<?> arg0, View arg1,
										int arg2, long arg3) {
									selectedBatchSecId = batchesSec.get(
											arg2).getBatchid();
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
								}
							});
				} else {
					batchsSec.setClickable(false);
					batchsSec.setEnabled(false);
					String[] m = new String[1];
					m[0] = "无子批次";
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							SpectorActivity.this,
							R.layout.simple_spinner_item, m);
					// 设置下拉列表的风格
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					// 将adapter 添加到spinner中
					batchsSec.setAdapter(adapter);

					batchsSec
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								@Override
								public void onItemSelected(
										AdapterView<?> arg0, View arg1,
										int arg2, long arg3) {
									selectedBatchSecId = 0;
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
								}
							});
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		// 拍照
		paizhaoBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(runnable).start();
				Intent intent = new Intent(SpectorActivity.this,
						PaiMaTypeMoreActivity.class);
				intent.putExtra("type", 2);
				startActivityForResult(intent, 10);
				// AlertDialog.Builder builder = new AlertDialog.Builder(
				// SpectorActivity.this);
				// builder.setTitle("选择方式");
				// builder.setItems(new String[] { "拍摄照片", "本地照片" },
				// new AlertDialog.OnClickListener() {
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which) {
				// if (which == 0) {
				// Intent intent = new Intent(
				// MediaStore.ACTION_IMAGE_CAPTURE);
				// image2SDcard(intent);
				// SpectorActivity.this
				// .startActivityForResult(intent,
				// 0);
				// } else if (which == 1) {
				// Intent intent = new Intent(
				// Intent.ACTION_GET_CONTENT);
				// intent.setType("image/*");
				// SpectorActivity.this
				// .startActivityForResult(intent,
				// 1);
				// }
				// }
				// });
				// builder.show();
			}
		});

		// 摄像
		shexiangBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(runnable).start();
				Intent intent = new Intent(SpectorActivity.this,
						PaiMaTypeMoreActivity.class);
				intent.putExtra("type", 3);
				startActivityForResult(intent, 20);
				// AlertDialog.Builder builder = new AlertDialog.Builder(
				// SpectorActivity.this);
				// builder.setTitle("选择方式");
				// builder.setItems(new String[] { "录制视频", "本地视频" },
				// new AlertDialog.OnClickListener() {
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which) {
				// if (which == 0) {
				// Intent intent = new Intent(
				// MediaStore.ACTION_VIDEO_CAPTURE);
				// intent.putExtra(
				// MediaStore.EXTRA_VIDEO_QUALITY,
				// 0);
				// SpectorActivity.this
				// .startActivityForResult(intent,
				// 2);
				// } else if (which == 1) {
				// Intent intent = new Intent(
				// Intent.ACTION_GET_CONTENT);
				// intent.setType("video/*");
				// SpectorActivity.this
				// .startActivityForResult(intent,
				// 3);
				// }
				// }
				// });
				// builder.show();
			}
		});
		saveToUpload.setOnClickListener(saveCallBack);
		// paiMa.setOnClickListener(paimaCallBack);
		backToIndex.setOnClickListener(backCallBack);
		spectorContent.setOnClickListener(editCallBack);
	}

	/**
	 * 拍码回调
	 */
	public Button.OnClickListener paimaCallBack = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					SpectorActivity.this);
			builder.setTitle("选择方式");
			builder.setItems(new String[] { "拍作业地码", "输作业地码" },
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (which == 0) {
								Intent intent = new Intent(Intents.Scan.ACTION);
								startActivityForResult(intent, 100);
							} else if (which == 1) {
								LayoutInflater inflater = LayoutInflater
										.from(SpectorActivity.this);
								View view = inflater.inflate(
										R.layout.dialog_edit_dapeng, null);
								final EditText text = (EditText) view
										.findViewById(R.id.dialog_edittext_dapeng);
								AlertDialog.Builder builder1 = new AlertDialog.Builder(
										SpectorActivity.this);
								builder1.setTitle("请输入作业地码");
								builder1.setView(view);
								builder1.setPositiveButton("确定",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												String contents = text
														.getText().toString()
														.trim();
												if (contents == null
														|| contents.equals("")) {
													Toast.makeText(
															SpectorActivity.this,
															"码内容为空",
															Toast.LENGTH_LONG)
															.show();
												} else {

													CodeActivationInfo activationInfo = new CodeActivationInfo();
													activationInfo
															.setStartcode(contents);
													activationInfo
															.setEnterpriseid(enterpriseId);
													activationInfo
															.setIsnew(isNew);
													progressDialog = ProgressDialog
															.show(SpectorActivity.this,
																	"提示",
																	"正在查询....",
																	true, false);
													PaimaAsyn paimaAsyn = new PaimaAsyn();
													paimaAsyn
															.execute(activationInfo);

												}
											}
										});
								builder1.setNegativeButton("取消",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {

											}
										});
								builder1.create().show();
							}
						}
					});
			builder.create().show();
		}
	};
	/**
	 * 上传
	 */
	public Button.OnClickListener saveCallBack = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {

			NcpRequestInfo ncpRequestInfo = new NcpRequestInfo();

			if (selectedBatchId == 0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						SpectorActivity.this);
				builder.setTitle("提示");
				builder.setMessage("请先拍码获取批次！");
				builder.setCancelable(false);
				builder.setNegativeButton("确定", new OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						saveToUpload.setEnabled(true);
						saveToUpload.setFocusable(true);
					}
				});

				builder.create().show();
			}
			ncpRequestInfo.setBatchid(selectedBatchId);

			if (isPublic) {
				ncpRequestInfo.setBatchidSec(-1);
			} else {
				// if (selectedBatchSecId == 0) {
				//
				// AlertDialog.Builder builder = new AlertDialog.Builder(
				// SpectorActivity.this);
				// builder.setTitle("提示");
				// builder.setMessage("请获取子批次！");
				// builder.setCancelable(false);
				// builder.setNegativeButton("确定", new OnClickListener() {
				// public void onClick(DialogInterface dialog,
				// int whichButton) {
				// }
				// });
				// builder.create().show();
				// return;
				// }
				ncpRequestInfo.setBatchidSec(selectedBatchSecId);
			}

			String ss = spectorContent.getText().toString();
			if (ss == null || ss.trim().equals("")) {
				new AlertDialog.Builder(SpectorActivity.this)
						.setTitle("提示")
						.setMessage("巡检内容不能为空")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).create().show();
				return;
			} else {
				ncpRequestInfo.setNcpcontent(spectorContent.getText()
						.toString());
			}

			try {
				List<PicturesInfo> picInfos = picGrid.getList();
				List<VideoInfo> videoInfos = videoGrid.getList();

				// if (picInfos.size() == 0 && videoInfos.size() == 0) {
				// AlertDialog.Builder builder = new AlertDialog.Builder(
				// SpectorActivity.this);
				// builder.setTitle("提示");
				// builder.setMessage("视频和图像不能同时为空！");
				// builder.setCancelable(false);
				// builder.setNegativeButton("确定", new OnClickListener() {
				// public void onClick(DialogInterface dialog,
				// int whichButton) {
				// SpectorActivity.this.picGrid = picGrid;
				// SpectorActivity.this.videoGrid = videoGrid;
				// }
				// });
				// builder.create().show();
				// return;
				// }

				ncpFiles = new ArrayList<NcpFile>();
				if ((picInfos == null || picInfos.size() == 0)
						&& (videoInfos == null || videoInfos.size() == 0)) {
					ncpRequestInfo.setNcpfilearr(null);
				} else {
					if (picInfos != null && picInfos.size() != 0) {
						for (int i = 0; i < picInfos.size(); i++) {
							NcpFile ncpFile = new NcpFile();
							ncpFile.setFiledir(picInfos.get(i).getPureName());
							ncpFile.setFiletype(1);
							ncpFile.setFiledescriptions(picInfos.get(i)
									.getDescription());
							ncpFiles.add(ncpFile);
						}
					}

					if (videoInfos != null && videoInfos.size() != 0) {
						for (int i = 0; i < videoInfos.size(); i++) {
							NcpFile ncpFile = new NcpFile();
							ncpFile.setFiledir(videoInfos.get(i).getVideourl());
							ncpFile.setPicdir(videoInfos.get(i).getImageurl());
							ncpFile.setFiletype(2);
							ncpFile.setFiledescriptions(videoInfos.get(i)
									.getDescription());
							ncpFiles.add(ncpFile);
						}
					}
					NcpFile[] resources = new NcpFile[ncpFiles.size()];
					for (int i = 0; i < ncpFiles.size(); i++) {
						resources[i] = ncpFiles.get(i);
					}
					ncpRequestInfo.setNcpfilearr(resources);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			ncpRequestInfo.setEnterpriseid(enterpriseId);
			ncpRequestInfo.setUsercode(usercode);
			ncpRequestInfo.setPersonid(personId);
			ncpRequestInfo.setUsername(username);
			ncpRequestInfo.setIsnew(isNew);
			//ncpRequestInfo.setFtpFile(loginResultInfo.getFtpfile());
			progressDialog = ProgressDialog.show(SpectorActivity.this, "提示",
					"正在保存数据....", true, false);

			SaveOperationAsyn saveOperationAsyn = new SaveOperationAsyn();
			saveOperationAsyn.execute(ncpRequestInfo);
		}

	};
	/*
	 * 返回主页按钮事件
	 */
	public Button.OnClickListener backCallBack = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			AlertDialog alert = new AlertDialog.Builder(SpectorActivity.this)
					.setTitle(getString(R.string.tip_back))
					.setMessage(getString(R.string.tip_back_description))
					.setCancelable(false)
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							SpectorActivity.this.finish();
						}
					}).create();
			alert.show();
		}
	};

	/*
	 * 编辑巡检内容
	 */
	public Button.OnClickListener editCallBack = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			View view = View.inflate(SpectorActivity.this,
					R.layout.dialog_content_edit, null);
			final EditText editText = (EditText) view
					.findViewById(R.id.dialog_edittext);
			final String contentOld = spectorContent.getText().toString()
					.trim();
			editText.setText(contentOld);
			AlertDialog alert = new AlertDialog.Builder(SpectorActivity.this)
					.setTitle("巡检内容").setCancelable(false).setView(view)
					.setNegativeButton("取消", null)
					.setPositiveButton("确定", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							AlertDialog dialog1 = (AlertDialog) (dialog);
							String contentNew = editText.getText().toString()
									.trim();
							if (!contentNew.equals(contentOld)) {
								spectorContent.setText(contentNew);
								// setListViewHeight(expandableListView);
							}
							dialog1.dismiss();
						}
					}).create();
			alert.show();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AlertDialog alert = new AlertDialog.Builder(SpectorActivity.this)
					.setTitle(getString(R.string.tip_back))
					.setCancelable(false)
					.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// 结束应用程序
							SpectorActivity.this.finish();
						}
					}).create();
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 拍码返回处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 10) {
			if (resultCode == 1) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				image2SDcard(intent);
				SpectorActivity.this.startActivityForResult(intent, 0);
			} else if (resultCode == 2) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				SpectorActivity.this.startActivityForResult(intent, 1);
			}
		} else if (requestCode == 20) {
			if (resultCode == 1) {
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
				SpectorActivity.this.startActivityForResult(intent, 2);
			} else if (resultCode == 2) {
				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setType("video/*");
				SpectorActivity.this.startActivityForResult(intent, 3);
			}
		} else if (resultCode == RESULT_OK) {

			if (requestCode == 100) {

				String contents = data.getStringExtra("SCAN_RESULT").trim();
				CodeActivationInfo activationInfo = new CodeActivationInfo();
				activationInfo.setStartcode(contents);
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setIsnew(isNew);
				progressDialog = ProgressDialog.show(SpectorActivity.this,
						"提示", "正在查询....", true, false);
				PaimaAsyn paimaAsyn = new PaimaAsyn();
				paimaAsyn.execute(activationInfo);
			} else if (requestCode == 0 || requestCode == 1) {
				// picGrid.onViewResult(requestCode, resultCode, data, 1, 1);
				picGrid.onViewResult(requestCode, resultCode, data, 1, 1, ftp,
						list);
			} else if (requestCode == 2 || requestCode == 3) {
				// videoGrid.onViewResult(requestCode, resultCode, data);
				if (videoGrid.isTypeOk(data)) {
					videoGrid.onViewResult(requestCode, resultCode, data, ftp);
					vioNewsTextView.setVisibility(View.VISIBLE);
					videoGrid.setVisibility(View.VISIBLE);
				} else {
					Toast.makeText(SpectorActivity.this, "暂不支持此格式文件上传",
							Toast.LENGTH_LONG).show();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private class PaimaAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SpectorActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SpectorActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					codeActivationResultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (codeActivationResultInfo.getResult() == 3010) {
						batchs.setEnabled(true);
						batches = codeActivationResultInfo.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(SpectorActivity.this, "批次列表空",
									Toast.LENGTH_LONG).show();
						} else {
							String[] m = new String[batches.size()];
							for (int i = 0; i < batches.size(); i++) {
								m[i] = batches.get(i).getBatchcode();
							}
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(
									SpectorActivity.this,
									R.layout.simple_spinner_item, m);
							// 设置下拉列表的风格
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							// 将adapter 添加到spinner中
							batchs.setAdapter(adapter);
						}

					} else {
						Toast.makeText(SpectorActivity.this,
								codeActivationResultInfo.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(3000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	private void LoadListDate() {
		// groupArray = new ArrayList<String>();
		// childArray = new ArrayList<List<View>>();
		//
		// groupArray.add("详细信息");

		// List<View> tempArray = new ArrayList<View>();
		//
		// View chileView01 = LayoutInflater.from(this).inflate(
		// R.layout.operation_child, null);
		TextView title01 = (TextView) findViewById(R.id.operation_batchs_title);
		title01.setText("生产批次");
		batchs = (Spinner) findViewById(R.id.operation_batchs_spinner_content);
		// tempArray.add(chileView01);
		//
		// View chileView02 = LayoutInflater.from(this).inflate(
		// R.layout.operation_child03, null);
		TextView title02 = (TextView) findViewById(R.id.operation_child03_title);
		title02.setText("公共/子批次");
		isPublicOrSec = (Spinner) findViewById(R.id.operation_child03_spinner_content);

		chileView06 = (LinearLayout) findViewById(R.id.operation_child03_linearlayout);

		TextView title06 = (TextView) findViewById(R.id.operation_child03_child_title);
		title06.setText("子批次");
		batchsSec = (Spinner) findViewById(R.id.operation_child03_child_spinner_content);

		// tempArray.add(chileView02);

		// View chileView04 = LayoutInflater.from(this).inflate(
		// R.layout.operation_child02, null);
		TextView title04 = (TextView) findViewById(R.id.operation_name_title);
		title04.setText("巡 检人员");
		spectorName = (EditText) findViewById(R.id.operation_name_content);
		spectorName.setFocusable(false);
		// operationContent.setMinLines(3);
		// tempArray.add(chileView04);

		// View chileView05 = LayoutInflater.from(this).inflate(
		// R.layout.operation_child02, null);
		TextView title05 = (TextView) findViewById(R.id.operation_child02_title);
		spectorContent = (EditText) findViewById(R.id.operation_child02_content);
		title05.setText("巡检内容");
		spectorContent.setMinLines(3);
		spectorContent.setVerticalScrollBarEnabled(true);
		spectorContent.setHint("点击编辑巡检内容");
		spectorContent.setFocusable(false);
		// tempArray.add(chileView05);
		//
		// for (int index = 0; index < groupArray.size(); ++index) {
		// childArray.add(tempArray);
		// }

	}

	public class ExpandableAdapter extends BaseExpandableListAdapter {
		Activity activity;

		public ExpandableAdapter(Activity a) {
			activity = a;
		}

		public Object getChild(int groupPosition, int childPosition) {
			return childArray.get(groupPosition).get(childPosition);
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		public int getChildrenCount(int groupPosition) {
			return childArray.get(groupPosition).size();
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			View childView = childArray.get(groupPosition).get(childPosition);
			return childView;
		}

		// group method stub
		public Object getGroup(int groupPosition) {
			return groupArray.get(groupPosition);
		}

		public int getGroupCount() {
			return groupArray.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			GroupViewHolder groupViewHolder;
			if (convertView == null) {
				groupViewHolder = new GroupViewHolder();
				convertView = LayoutInflater.from(activity).inflate(
						R.layout.operation_group, null);
				groupViewHolder.groupItemText = (TextView) convertView
						.findViewById(R.id.operation_group_title);
				convertView.setTag(groupViewHolder);
			} else {
				groupViewHolder = (GroupViewHolder) convertView.getTag();
			}

			groupViewHolder.groupItemText
					.setText(groupArray.get(groupPosition));

			return convertView;
		}

		public boolean hasStableIds() {
			return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

		private class GroupViewHolder {
			TextView groupItemText;
		}
	}

	public void setListViewHeight(ExpandableListView listView) {

		ListAdapter listAdapter = listView.getAdapter();

		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0); // 计算子项View 的宽高
			totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	private ExpandableListView.OnGroupExpandListener groupExpandListener = new ExpandableListView.OnGroupExpandListener() {

		@Override
		public void onGroupExpand(int groupPosition) {
			// TODO Auto-generated method stub
			setListViewHeight(expandableListView);
		}
	};

	private ExpandableListView.OnGroupCollapseListener groupCollListener = new ExpandableListView.OnGroupCollapseListener() {

		@Override
		public void onGroupCollapse(int groupPosition) {
			// TODO Auto-generated method stub
			setListViewHeight(expandableListView);
		}
	};

	public void image2SDcard(Intent intent) {
		File sdDir;
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Toast.makeText(SpectorActivity.this, "无SD卡", Toast.LENGTH_SHORT)
					.show();
			return;
		} else {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}

		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		File file = new File(sdDir.getPath() + "/AgricultureSystem/Image/");
		file.mkdirs();// 创建文件夹
		String dataStr = formatter.format(date);
		String newCapturePhotoPath = null;

		newCapturePhotoPath = sdDir.getPath() + "/AgricultureSystem/Image/"
				+ dataStr + ".jpg";

		String name = newCapturePhotoPath;

		picGrid.setName(name);
		picGrid.setNewCapturePhotoPath(newCapturePhotoPath);

		Uri uri = Uri.fromFile(new File(newCapturePhotoPath));
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	}

	private class SaveOperationAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SpectorActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SpectorActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);
					if (resultInfo.getResult() == 3110) {
						Toast.makeText(SpectorActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
						SpectorActivity.this.finish();
					} else {
						Toast.makeText(SpectorActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			saveToUpload.setEnabled(true);
			saveToUpload.setFocusable(true);
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			NcpRequestInfo request = (NcpRequestInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(3100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	public Handler handler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			Log.i("mylog", "请求结果为-->" + "0000000000000000000");
		}
	};

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			ftp = new FTPClient();
			ftp.setCharset("utf-8");
			ftp.setType(FTPClient.TYPE_BINARY);
			try {
				// ftp.connect(getString(R.string.ftp_url_ip));

//				URL url = new URL(domainName);
//				int port = url.getPort() < 1 ? 21 : url.getPort();
//				Log.i("Ftp server listening on address============= ",
//						url.toString());
//				ftp.connect(url.getHost(), port);
//				ftp.login(name.trim(), pwd.trim());
//				String path = url.getPath();
//				if (!TextUtils.isEmpty(path) && !path.equals("/")) {
//					if (isExist(path + loginResultInfo.getFtpfile().trim())) {
//
//					} else {
//						// 改变目录
//						ftp.changeDirectory(path);
//						// 不存在该目录，则创建目录
//						ftp.createDirectory(loginResultInfo.getFtpfile());
//						ftp.changeDirectory(loginResultInfo.getFtpfile());
//					}
//				} else {
//					ftp.changeDirectory(loginResultInfo.getFtpfile());
//				}
				// ftp.connect(domainName);
				// ftp.login(name, pwd);
				//
				// ftp.setType(FTPClient.TYPE_AUTO);
				// ftp.setCharset("utf8");

				// try {
				// list = ftp.listNames();
				// } catch (FTPDataTransferException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// } catch (FTPAbortedException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// } catch (FTPListParseException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				// boolean isCunzai = false;
				// for (String string1 : list) {
				// // Log.d("H3c", file.getName());
				// if (loginResultInfo.getFtpfile().equals(string1)) {
				// isCunzai = true;
				// }
				// }
				//
				// // Log.d("currentDirectory", ftp.currentDirectory());
				// // 是不是在该文件夹下
				// if (!isCunzai) {
				// // 不存在该目录，则创建目录
				// ftp.createDirectory(loginResultInfo.getFtpfile());
				// }
				// // 改变路径
				// ftp.changeDirectory(loginResultInfo.getFtpfile());
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.sendEmptyMessage(0);
		}
	};

	public boolean isExist(String dir) {
		try {
			ftp.changeDirectory(dir);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public void closePicView() {

		picNewsTextView.setVisibility(View.GONE);
	}

	public void closeVedioView() {

		vioNewsTextView.setVisibility(View.GONE);
	}

	public void showView() {
		picGrid.setVisibility(View.VISIBLE);
		picNewsTextView.setVisibility(View.VISIBLE);
	}

	public void hideView() {
		picGrid.setVisibility(View.GONE);
		picNewsTextView.setVisibility(View.GONE);
	}
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	if(ftp!=null){
    		ftp = null;
    	}
    	if(adapter!=null){
    		adapter = null;
    	}
    }
}
